'use strict';

const Controller = require('egg').Controller;

class CarController extends Controller {
    //添加
    async add() {
        let {ctx,service} = this;
        let {uid,pid} = ctx.request.body;
        console.log("---------------------------",uid,pid)
        if(uid && pid){
            //先做排重
            let target = await service.car.select(uid,pid);
            console.log(target);
            if(target.length){
                //已经添加过商品
                await service.car.update(uid,pid,target[0].num+1);
                ctx.body = {
                    code:1,
                    msg:'添加成功'
                }
            }else{
                console.log("======",uid,pid)
                //没有添加过
                // try{    
                    await service.car.add(uid,pid,1);
                    ctx.body = {
                        code:1,
                        msg:'添加成功'
                    }
                // }catch(e){
                //     ctx.body = {
                //         code:0,
                //         msg:e
                //     }
                // }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数为空'
            }
        }
    }

    //更新
    async update(){
        let {ctx,service} = this;
        let {id,num} = ctx.request.body;
        
        if(id && num){
            try{
                await service.car.carUpdate(id,num);
                ctx.body = {
                    code:1,
                    msg:'更新成功'
                }
            }catch(e){
                ctx.body = {
                    code:0,
                    msg:e
                }
            }
        }else{
            ctx.body = {
                code:2,
                msg:'参数为空'
            }
        }
    }

    //购物车列表
    async carlist(){
        let {ctx,service} = this;

        let {uid} = ctx.query;

        let carlist = await service.car.carlist(uid);

        ctx.body = {
            code:1,
            data:carlist
        }
    }
}

module.exports = CarController;


